from django.shortcuts import render
from django.http import HttpResponse
import re
from django.core.urlresolvers import reverse
class AdminLoginMiddleware:
    def __init__(self,get_response):
        self.get_response = get_response

    def __call__(self, request):

        # 检测当前的请求是否已经登录,如果已经登录,.则放行,如果未登录,则跳转到登录页
        # 获取当前用户的请求路径  /admin/开头  但不是 /admin/login/  /admin/dologin/   /admin/verifycode
        urllist = ['/myadmin/login/','/myadmin/verifycode/']
        # 判断是否进入了后台,并且不是进入登录页面
        if re.match('/myadmin/',request.path) and request.path not in urllist:
            # 检测session中是否存在 adminlogin的数据记录
            if request.session.get("_auth_user_id",None) is None:
                # 如果在session没有记录,则证明没有登录,跳转到登录页面
                return HttpResponse('<script>alert("请先登录");location.href="/myadmin/login/";</script>')
        # qturlist = [
        #         reverse("myhome_cart_index"),
        #         reverse("myhome_cart_money"),
        #         reverse("myhome_cart_submit"),
        #         reverse("myhome_cart_del"),
        #         reverse("myhome_citys"),
        #         reverse("myhome_order_order"),
        #         reverse("myhome_order_manage"),
        #         reverse("myhome_info_update"),
        #         reverse("myhome_order_addrIndex"),
        #         reverse("myhome_address"),
        #         reverse("myhome_place_order"),
        #         reverse("myhome_over")
        #         ]  
       # 如果当前请求的路径,是需要登录的
        # if request.path in qturlist:
        #     # 检测是否已经登录
        #     if not request.session.get('VipUser'):
        #         # 需要登录,跳转到登录页
        #         return HttpResponse('<script>alert("请先登录");location.href="myhome/login/?nextpath='+request.path+'";</script>')
        print(request.GET,'--------------')
        response = self.get_response(request)
        return response
    
